import * as turf from "@turf/turf";
import mapboxgl from "mapbox-gl";

export class MeasureTool {
  constructor(map, mapDraw) {
    this.map = map;
    this.Draw = mapDraw;
    this.featureId = null;
    this.markerElement = this.createMarkerElement();
    this.clickHandler = null;
    this.distanceMarkers = []; // 添加数组存储距离标记
    
    // 绑定事件
    this.bindEvents();
  }

  // 创建标记元素
  createMarkerElement(text = '') {
    const markerElement = document.createElement("div");
    markerElement.className = "marker";
    markerElement.style.backgroundColor = "transparent";
    markerElement.style.width = "100px";
    markerElement.style.height = "30px";
    markerElement.style.display = "flex";
    markerElement.style.alignItems = "center";
    markerElement.style.justifyContent = "center";
    if (text) {
      markerElement.innerHTML = `<span style="color: black; font-size: 14px;">${text}</span>`;
    }
    return markerElement;
  }

  // 绑定绘制事件
  bindEvents() {
    this.map.on("draw.create", (e) => this.updateDraw(e));
    this.map.on("draw.delete", (e) => this.updateDraw(e));
    this.map.on("draw.update", (e) => this.updateDraw(e));
    this.map.on("draw.modechange", () => this.holdMode());
    this.map.on("draw.selectionchange", () => this.holdMode());
  }

  // 更新绘制
  updateDraw() {
    let data = this.Draw.getAll();
    let currentMode = this.Draw.getMode();

    if (currentMode === "draw_polygon") {
      this.measureArea(data);
    } else if (currentMode === "draw_line_string") {
      this.measureDistance(data);
    }
  }

  // 测量面积
  measureArea(data) {
    if (data.features.length > 0) {
      this.featureId = data.features[0].id;
      let coordinates =
        data.features[data.features.length - 1].geometry.coordinates;
      let polygon = turf.polygon(coordinates);
      let center = turf.centerOfMass(polygon);
      let area = turf.area(polygon);
      let area1 = Math.round(area * 100) / 100;

      this.markerElement.innerHTML = `<span style="color: black; font-size: 14px;">
        ${
          area1 > 10000 ? (area1 / 10000).toFixed(2) + " km²" : area1 + " m²"
        }</span>`;

      new mapboxgl.Marker(this.markerElement)
        .setLngLat(center.geometry.coordinates)
        .addTo(this.map);
    }
  }

  // 格式化距离
  formatDistance(distance) {
    return distance >= 1
      ? `${Math.round(distance * 100) / 100} km`
      : `${Math.round(distance * 1000 * 100) / 100} m`;
  }

  // 测量距离
  measureDistance(data) {
    // 清除之前的距离标记
    this.clearDistanceMarkers();
    
    if (data.features.length > 0) {
      this.featureId = data.features[0].id;
      let coordinates = data.features[data.features.length - 1].geometry.coordinates;
      let totalLength = 0;

      // 计算每个节点的累计距离并显示
      for (let i = 1; i < coordinates.length; i++) {
        // 计算从起点到当前节点的累计距离
        let accumulatedLength = 0;
        for (let j = 0; j < i; j++) {
          let from = turf.point(coordinates[j]);
          let to = turf.point(coordinates[j + 1]);
          let options = { units: "kilometers" };
          let distance = turf.distance(from, to, options);
          accumulatedLength += distance;
        }
        totalLength = accumulatedLength;

        // 在每个节点处创建标记显示累计距离
        if (i < coordinates.length - 1) {
          // 非终点显示累计距离
          const nodeMarker = new mapboxgl.Marker(
            this.createMarkerElement(this.formatDistance(accumulatedLength))
          )
            .setLngLat(coordinates[i])
            .addTo(this.map);
          
          this.distanceMarkers.push(nodeMarker);
        } else {
          // 终点显示总长
          const totalMarker = new mapboxgl.Marker(
            this.createMarkerElement(`总长: ${this.formatDistance(totalLength)}`)
          )
            .setLngLat(coordinates[i])
            .addTo(this.map);
          
          this.distanceMarkers.push(totalMarker);
        }
      }
    }
  }

  // 清除距离标记
  clearDistanceMarkers() {
    this.distanceMarkers.forEach(marker => marker.remove());
    this.distanceMarkers = [];
  }

  // 保持模式
  holdMode() {
    this.Draw.changeMode("simple_select", { featureId: this.featureId });
  }

  // 开始测量
  startMeasure(type, flag) {
    this.deleteAll();
    if (type === "distance") {
      this.Draw.changeMode("draw_line_string", {});
    } else if (type === "area") {
      this.Draw.changeMode("draw_polygon", {});
    } else if (type === "point") {
      this.getMousePosition(flag);
    }
  }

  // 获取鼠标坐标
  getMousePosition(flag) {
    // 先移除可能存在的点击事件
    if (this.clickHandler) {
      this.map.off("click", this.clickHandler);
      this.clickHandler = null;
    }

    if (flag) {
      // 创建新的点击事件处理器
      this.clickHandler = (e) => {
        const { lng, lat } = e.lngLat;
        // 显示坐标
        this.markerElement.innerHTML = `<span style="color: black; font-size: 14px;">${lng}, ${lat}</span>`;
        new mapboxgl.Marker(this.markerElement)
          .setLngLat([lng, lat])
          .addTo(this.map);
        
        // 清除绘制
        this.Draw.deleteAll();
        
        // 创建点要素
        const point = {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [lng, lat]
          }
        };
        
        // 添加点
        this.Draw.add(point);
      };

      // 绑定点击事件
      this.map.on("click", this.clickHandler);
    }
  }

  // 删除所有
  deleteAll() {
    this.Draw.deleteAll();
    this.featureId = null;
    // 删除标记
    this.markerElement.remove();
    // 清除距离标记
    this.clearDistanceMarkers();
    // 移除点击事件
    if (this.clickHandler) {
      this.map.off("click", this.clickHandler);
      this.clickHandler = null;
    }
  }
}
